package com.CatTalkApi.Servlet;

import com.CatTalkApi.DAO.DataBaseContext;
import com.CatTalkApi.DAO.Passage;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/UpdatePassage")
public class UpdatePassage extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "application/json;");
        System.out.println("Update Passage Method: " + req.getMethod());
        //配置跨域
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH");
        resp.setHeader("Access-Control-Allow-Headers", "authorization, content-type,token,identify");
        resp.setHeader("Access-Control-Expose-Headers", "X-forwared-port, X-forwarded-host");
        resp.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
        super.service(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sql = "UPDATE `catwebdatabase`.`passage` SET `Body` = '%s', `Title` = '%s' WHERE (`Passage_ID` = '%d');";
        JSONObject jsonObject = JsonReader.receivePost(req);
        Passage passage = new Passage();
        passage.Body = (String) jsonObject.get("body");
        passage.Title = (String) jsonObject.get("title");
        passage.UsrId = (int) jsonObject.get("usrId");
        passage.Id = (int) jsonObject.get("id");
        try {
            int count = DataBaseContext.getInstance().GetStmt().executeUpdate(String.format(sql, passage.Body, passage.Title, passage.Id));
            if (count == 0) {
                resp.setStatus(424);
            } else {
                resp.setStatus(200);
            }
            DataBaseContext.getInstance().Close();
            resp.getWriter().write("Update Rows " + count);
        } catch (SQLException throwables) {
            resp.setStatus(500);
            resp.getWriter().write(throwables.getMessage());
            throwables.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(500);
        resp.getWriter().write("Method Not Allow");
        super.doGet(req, resp);
    }
}
